﻿using System.Linq;
using System.Windows;
using System.Windows.Controls.Primitives;
using StockholmsStad.Windows.UI.Modules.Couple.Models;
using StockholmsStad.Runtime.Serialization.DataContract;
using System.Windows.Controls;
using System;
using System.Windows.Data;
using StockholmsStad.Windows.UI.Modules.Couple.Interfaces;
using System.Collections.Generic;
using StockholmsStad.Windows.UI.Modules.Couple.BusinessEntities;

namespace StockholmsStad.Windows.UI.Modules.Couple.Controls
{
    /// <summary>
    /// Interaction logic for TabItemCerermony.xaml
    /// </summary>
    public partial class CeremonyDetailsControl
    {
        private readonly ICeremonyService ceremonyService;
        private List<ValueIdPair> ceremonyLanguages;
        private List<ValueIdPair> certificateLanguages;
        private List<CeremonySpecialNeed> ceremonyspecialNeeds;

        private CeremonyPresentationModel model;

        public CeremonyDetailsControl(ICeremonyService service)
        {
            ceremonyService = service;
            Initialized += CeremonyDetailsControl_Initialized;
            InitializeComponent();

            KeyUp += UserControl_KeyUp;

            Loaded += new RoutedEventHandler(CeremonyDetailsControl_Loaded);
            DataContextChanged += CeremonyDetailsControl_DataContextChanged;

            InterpreterCheckBox.Checked += InterpreterCheckBox_Checked;
            InterpreterCheckBox.Unchecked += InterpreterCheckBox_Unchecked;
            //IssuedDateTextBox.TextChanged += IssuedDateTextBox_TextChanged;
            //HPLatestDateTextBox.TextChanged += HPLatestDateTextBox_TextChanged;
            SpecialNeedsRadioButtonList.SelectionChanged += SpecialNeedsRadioButtonList_SelectionChanged;
            CertificateLanguagesComboBox.SelectionChanged += CertificateLanguagesComboBox_SelectionChanged;
        }

        private void CeremonyDetailsControl_Loaded(object sender, RoutedEventArgs e)
        {
            if(model != null && model.TicketId.HasValue)
            {
                DataContext = ceremonyService.GetCeremony(model.TicketId.Value);
            }
        }

        void HPLatestDateTextBox_TextChanged(object sender, EventArgs e)
        {
            ToggleButtons();
        }

        private void InterpreterCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            ToggleButtons();
        }

        private void InterpreterCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            ToggleButtons();
        }

        private void IssuedDateTextBox_TextChanged(object sender, EventArgs e)
        {
            HPHasArrivedCheckBox.IsChecked = IssuedDateTextBox.SelectedDate.HasValue;

            ToggleButtons();
        }

        private void CeremonyDetailsControl_Initialized(object sender, EventArgs e)
        {
            ceremonyLanguages = ceremonyService.GetCeremonyLanguages();
            certificateLanguages = ceremonyService.GetCertificateLanguages();
            ceremonyspecialNeeds = ceremonyService.GetSpecialNeeds();

            SpecialNeedsRadioButtonList.ItemsSource = ceremonyspecialNeeds;
            CeremonyLanguagesRadioButtonList.ItemsSource = ceremonyLanguages;
            CertificateLanguagesComboBox.ItemsSource = certificateLanguages;
        }

        private void CeremonyDetailsControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            model = DataContext as CeremonyPresentationModel;

            SpecialNeedsRadioButtonList.SelectedItems.Clear();

            if (model != null && model.TicketId > 0)
            {
                SetSelectedItems();
            }
        }

        private void SetSelectedItems()
        {
            if (model.CertificateLanguage != null)
            {
                CertificateLanguagesComboBox.SelectedValue =
                    certificateLanguages.Where(l => l.Name == model.CertificateLanguage.Name).FirstOrDefault();
            }

            if (model.CeremonyLanguage != null)
            {
                CeremonyLanguagesRadioButtonList.SelectedItem =
                    ceremonyLanguages.Where(l => l.Name == model.CeremonyLanguage.Name).FirstOrDefault();
            }

            if (model.CeremonySpecialNeeds != null)
            {
                foreach(var item in model.CeremonySpecialNeeds)
                {
                    var selectedItem = FindItem(item.Name);

                    if (selectedItem != null)
                        SpecialNeedsRadioButtonList.SelectedItems.Add(selectedItem);
                }
            }
        }

        // bugg, hur f-n sätter man items till selected egentligen????
        private ValueIdPair FindItem(string name)
        {
            foreach (var item in SpecialNeedsRadioButtonList.Items)
            {
                var selected = item as ValueIdPair;
                if (selected != null && selected.Name == name)
                    return selected;
            }

            return null;
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression be = HPHasArrivedCheckBox.GetBindingExpression(ToggleButton.IsCheckedProperty);
            be.UpdateSource();

            be = HPEarliestTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            //be = HPLatestDateTextBox.GetBindingExpression(DateTimePicker.SelectedDateProperty);
            //be.UpdateSource();

            //be = IssuedDateTextBox.GetBindingExpression(DateTimePicker.SelectedDateProperty);
            //be.UpdateSource();

            model.HPLatestDate = HPLatestDateTextBox.SelectedDate;
            model.HPIssuedDate = IssuedDateTextBox.SelectedDate;

            // Bugg bugg bugg!!!!!! 
            //be = CeremonyLanguagesRadioButtonList.GetBindingExpression(Selector.SelectedItemProperty);
            //be.UpdateSource();
            model.CeremonyLanguage = (ValueIdPair)CeremonyLanguagesRadioButtonList.SelectedItem;

            be = OtherLanguageTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            be = InterpreterCheckBox.GetBindingExpression(ToggleButton.IsCheckedProperty);
            be.UpdateSource();

            be = CertificateLanguagesComboBox.GetBindingExpression(Selector.SelectedItemProperty);
            be.UpdateSource();

            // Ska man kunna lägga till förrättare?? Isf ska dessa inte kommenteras bort
            //be = MinisterFirstNameTextBox.GetBindingExpression(TextBox.TextProperty);
            //be.UpdateSource();

            //be = MinisterLastNameTextBox.GetBindingExpression(TextBox.TextProperty);
            //be.UpdateSource();

            // Ännu ett hack för att få multiple combobox att funka....
            if(SpecialNeedsRadioButtonList.SelectedItems != null)
            {
                if(model.CeremonySpecialNeeds == null)
                    model.CeremonySpecialNeeds = new List<CeremonySpecialNeed>();
                
                model.CeremonySpecialNeeds.Clear();

                foreach (CeremonySpecialNeed item in SpecialNeedsRadioButtonList.SelectedItems)
                {
                    model.CeremonySpecialNeeds.Add(item);
                }
            }

            be = NoteTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            ToggleButtons();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            SpecialNeedsRadioButtonList.SelectedItems.Clear();

            if(model != null)
            {
                HPHasArrivedCheckBox.IsChecked = model.HPHasArrived;
                HPEarliestTextBox.Text = model.HPEarliestDate.HasValue ? model.HPEarliestDate.Value.ToString("yyyy-MM-dd") : "";

                HPLatestDateTextBox.SelectedDate = model.HPLatestDate.HasValue ? model.HPLatestDate.Value : new DateTime();

                IssuedDateTextBox.SelectedDate = model.HPIssuedDate.HasValue ? model.HPIssuedDate.Value : new DateTime();

                HPHasArrivedCheckBox.IsChecked = model.HPIssuedDate.HasValue ? true : false;

                CeremonyLanguagesRadioButtonList.SelectedValue = model.CeremonyLanguage;
                OtherLanguageTextBox.Text = model.OtherLanguage;
                InterpreterCheckBox.IsChecked = model.Interpreter;
                CertificateLanguagesComboBox.SelectedValue = model.CertificateLanguage;
                MinisterFirstNameTextBox.Text = model.MinisterFirstName;
                MinisterLastNameTextBox.Text = model.MinisterLastName;

                //SpecialNeedsRadioButtonList
                SetSelectedItems();

                NoteTextBox.Text = model.Note;

                ToggleButtons();
            }
        }

        private void UserControl_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            ToggleButtons();
            e.Handled = true;
        }

        private void ToggleButtons()
        {
            bool enabled = false;

            enabled = !HPHasArrivedCheckBox.IsChecked.Equals(model.HPHasArrived);

            if (model.HPEarliestDate.HasValue)
                enabled = !HPEarliestTextBox.Text.Equals(model.HPEarliestDate.Value.ToString("yyyy-MM-dd")) || enabled;

            if (model.HPLatestDate.HasValue)
                enabled = !HPLatestDateTextBox.SelectedDate.Equals(model.HPLatestDate.Value.ToString("yyyy-MM-dd")) || enabled;

            if (IssuedDateTextBox.SelectedDate.HasValue)
            {
                if (model.HPIssuedDate.HasValue)
                    enabled = !IssuedDateTextBox.SelectedDate.Equals(model.HPIssuedDate.Value.ToString("yyyy-MM-dd")) || enabled;
                else
                    enabled = true;
            }

            if (model.HPIssuedDate.HasValue)
            
            if (model.HPEarliestDate.HasValue)
                enabled = !HPEarliestTextBox.Text.Equals(model.HPEarliestDate.Value.ToString("yyyy-MM-dd")) || enabled;

            var cerLangItem = CeremonyLanguagesRadioButtonList.SelectedValue as ValueIdPair;

            if (cerLangItem != null)
                enabled = !cerLangItem.Name.Equals(model.CeremonyLanguage.Name) || enabled;

            var certLangItem = CertificateLanguagesComboBox.SelectedValue as ValueIdPair;

            if (certLangItem != null)
                enabled = !certLangItem.Name.Equals(model.CertificateLanguage.Name) || enabled;

            enabled = !OtherLanguageTextBox.Text.Equals(model.OtherLanguage) || enabled;
            enabled = !InterpreterCheckBox.IsChecked.Equals(model.Interpreter) || enabled;
            enabled = !MinisterFirstNameTextBox.Text.Equals(model.MinisterFirstName) || enabled;
            enabled = !MinisterLastNameTextBox.Text.Equals(model.MinisterLastName) || enabled;
            enabled = !NoteTextBox.Text.Equals(model.Note) || enabled;

            if(model.CeremonySpecialNeeds != null)
            {
                var selectedNeeds = model.CeremonySpecialNeeds.Where(n => n.IsSelected).ToList();
                enabled = !SpecialNeedsRadioButtonList.SelectedItems.Count.Equals(selectedNeeds.Count) || enabled;
            }

            SaveButton.IsEnabled = enabled;// !extrastTextBox.Text.Equals(Model.ExtrasInfo);
            CancelButton.IsEnabled = enabled;// !extrastTextBox.Text.Equals(Model.ExtrasInfo);
        }

    }
}
